package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Infile;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.InfileService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/24.
 */
@Controller
@RequestMapping(value = "/com/infile")
public class InfileController extends BaseController {
    private static final long serialVersionUID = 3851126191015778189L;

    @Autowired
    private InfileService infileService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private UserService userService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private RemindService remindService;


    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> dictItems = getDictItems(user,"infileType");
        if (StringUtils.isNotEmpty(keyId)){
            Infile infile=infileService.get(keyId);
            String fileId ="";
            if(infile.getFile() != null && infile.getFile().size()>0){
                for(FileManage f:infile.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("fileId", fileId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("infile", infile);
        }
        model.addAttribute("dictItems", dictItems);
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/infile_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            Infile infile=infileService.get(keyId);
            if(infile.getFile() != null && infile.getFile().size()>0){
                for(FileManage f:infile.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("infile", infile);
            model.addAttribute("fileId", fileId);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/infile_read";
    }

    /**
     * 保存Model数据
     */
    private Infile saveModel(User user, String keyId, String dictItemId, String fileNo, String name,String datReceived,
                             String datLine,String userIds, String fileIds) {

        Infile infile = null;
        if (StringUtils.isBlank(keyId)) {
            infile = new Infile();
            infile.setCreater(user);
            infile.setCompany(user.getCompany());
        } else {
            infile = infileService.get(keyId);
        }

        if (StringUtils.isNotBlank(dictItemId)) {
            DictItem dictItem = dictItemService.get(dictItemId);
            infile.setDictItem(dictItem);
        }

        if (StringUtils.isNotBlank(fileNo)) {
            infile.setFileNo(fileNo);
        }

        if (StringUtils.isNotBlank(name)) {
            infile.setName(name);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(datReceived)) {
            try {
                infile.setDatReceived(sdf.parse(datReceived));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(datLine)) {
            try {
                infile.setDatLine(sdf.parse(datLine));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isNotBlank(userIds)) {
            String[] uids = StringUtils.split(userIds,",");
            HashSet<User> users = new HashSet<User>();
            for (String uid : uids) {
                User u = userService.get(uid);
                users.add(u);
            }
            infile.setViewers(users);
        }

        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        infile.setFile(fileManageList);

        if (infile.getForm() == null) {
            infile.setForm("收文登记表");
        }

        return infile;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String dictItemId, String fileNo, String name,String datReceived,
                       String datLine,String userIds,String fileIds){

        Map<String,Object> rMap=new HashMap<String,Object>();
        Infile infile = saveModel(user, keyId, dictItemId, fileNo, name, datReceived, datLine, userIds, fileIds);
        if(StringUtils.isNotEmpty(keyId)){
            infileService.update(infile);
            rMap.put("message", "更新成功");
        } else {
            infileService.save(infile, "com.fz.us.oa.core.entity.com.Infile");
            rMap.put("message","保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String dictItemId, String fileNo, String name,String datReceived,
                         String datLine,String userIds, String fileIds, String curDutyId, String comment){

        Map<String,Object> rMap=new HashMap<String,Object>();
        Infile infile = saveModel(user, keyId, dictItemId, fileNo, name, datReceived, datLine, userIds, fileIds);

        if (StringUtils.isNotEmpty(keyId)) {
            infileService.approve(infile, dutyService.get(curDutyId), comment);
        } else {
            infileService.commit(infile, "com.fz.us.oa.core.entity.com.Infile", dutyService.get(curDutyId));
        }

        if(infile.getProcessState().name().equals("Finished")){
            doFinished(infile);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Infile infile=infileService.get(keyId);
        infileService.approve(infile, dutyService.get(curDutyId), comment);

        if(infile.getProcessState().name().equals("Finished")){
            doFinished(infile);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(Infile infile){
        for(User user1:infile.getViewers()){
            Remind remind = new Remind();
            remind.setUser(user1);
            remind.setBussinessKey("infile");
            remind.setKeyId(infile.getId());
            remind.setContent("您有一份收文需要查看，请查看");
            remindService.save(remind);
        }
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Infile infile=infileService.get(keyId);
            infileService.back(infile, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Infile infile=infileService.get(keyId);
            infileService.deny(infile, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order =  Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});

        //所有单子
        searchResult = infileService.paging(null, null, order,
                "com.fz.us.oa.core.entity.com.Infile",
                new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished}, params);

        List<Infile> infileList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Infile infile: infileList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(infile.getId())?"":infile.getId());
            rMap.put("name", StringUtils.isEmpty(infile.getName())?"":infile.getName());
            rMap.put("fileNo", StringUtils.isEmpty(infile.getFileNo())?"":infile.getFileNo());

            if (infile.getDictItem() != null) {
                DictItem sealDictItem = infile.getDictItem();
                rMap.put("dictItemId", sealDictItem.getId());
                String definedName = dictItemService.getDefinedName(infile.getCompany().getId(), sealDictItem.getId());
                rMap.put("dictItemName", StringUtils.isEmpty(definedName)?sealDictItem.getName():definedName);
            }

            rMap.put("datReceived", infile.getDatReceived()==null?"": DataUtil.DateToString(infile.getDatReceived()));
            rMap.put("txtStatus", infile.getProcessState().value());
//            rMap.put("txtStatus", infile.getTxtStatus());
//        map.put("creater", entity.getCreater()==null?"": entity.getCreater().getName());
//        map.put("processStateName", entity.getProcessState()==null?"": entity.getProcessState().value());
//        map.put("createTime", entity.getCreateTime()==null?"": DataUtil.DateTimeToString(entity.getCreateTime()));
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 失效
     */
    @RequestMapping(value = "invalid/{keyId}", method = RequestMethod.POST)
    public Object saveDialogReturn(@CurrentUser User user,@PathVariable String keyId) throws ParseException {
        Infile infile = infileService.get(keyId);

        if (infile==null) {
            return resultService.fail("对应的业务数据已丢失！");
        }

        infile.setTxtStatus("已失效");
        infile.setProcessState(FlowEnum.ProcessState.Destroy);
        return ajaxJson(infileService.saveEntity(infile));
    }

}
